require "classes/stage"
require "classes/menu"

--The Main class will control the game state and it´s changes

-- Game State variable defines which screen the game is currently
-- Menu, stage, GameOver, GameWon, credits
local gameState
local gameWon = love.graphics.newImage("images/menu/game-won.png")
local gameOver = love.graphics.newImage("images/menu/game-over.png")
local credits = love.graphics.newImage("images/menu/credits.png")
local gameSound = love.audio.newSource("sounds/The Descent.mp3")
 
local backgroundWidth = 720
local backgroundHeight = 570

function love.load()
  love.window.setTitle("A Fuga")
  love.window.setMode(backgroundWidth, backgroundHeight)

-- Game starts on the menu
  gameState = "menu"
  gameSound:setLooping(true)
  love.audio.play(gameSound)
  menu:load()
  stage:load()
end

function love.draw()
  if(gameState == "menu") then
    menu:draw()
  elseif(gameState == "stage") then
    stage:draw()
      love.graphics.print("Frame Rate: "..love.timer.getFPS(), 500, 520)
      love.graphics.print("Game State: "..gameState, 100, 520)
      love.graphics.print("Aperte ESC para sair do jogo.", 100, 540)
   elseif(gameState == "credits") then
    love.graphics.draw(credits, 0, 0)
  elseif(gameState == "gamewon") then
    love.graphics.draw(gameWon, 0, 0)
  elseif(gameState == "gameover") then
    love.graphics.draw(gameOver, 0, 0)
  end
end

function love.update(dt)
  if(gameState == "menu") then
    menu:update(dt)
  elseif(gameState == "stage") then
    stage:update(dt)
    -- Checks if the player has passed stage or been found
    if stage.stageState == "completed" then
      -- Game Won
      gameState = "gamewon"
    elseif stage.stageState == "terminated" then
      -- Game Over
      love.timer.sleep( 1 )
      gameState = "gameover"
    end
  end
end

function love.keypressed( key )
  if key == "escape" then
    gameState = "menu"
    stage:reset()
  end
  
  if(gameState == "stage") then
    stage:keypressed(key)
  end
end

function love.mousepressed(x, y, button)
  if(gameState == "menu") then
    if(menu:startButtonClicked(x,y, button) == true) then
      gameState = "stage"
    elseif(menu:creditsButtonClicked(x,y, button) == true) then
      gameState = "credits"
    end 
  end
end